﻿using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System;

public class SocketClient : MonoBehaviour {
	public int intervalSecond = 1;	
	
	private float saveTime = 0.0f;
	
	private int port = 8309;
	private string hostIP = "192.168.1.133";
	private Socket client;
	private byte[] buffer = new byte[1024];

	void Start () {
		IPEndPoint remoteEp = new IPEndPoint(IPAddress.Parse(hostIP), port);
		client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		client.BeginConnect(remoteEp, new AsyncCallback(ConnectCallback), client);
	}
	
/*
	void Update () {
		if(checkSend() == 1){
			string sendStr = "中国人啊";
			byte[] bs = Encoding.UTF8.GetBytes(sendStr);
			Send(bs, 10006);
		}
	}
*/
	public void Send(string data){
		byte[] bs = Encoding.UTF8.GetBytes(data);
		SendData (bs, 10006);
	}
	
	void OnApplicationQuit() {
		if(client != null && client.Connected){
			client.Close();
		}
	}
	
	int checkSend(){
		float curTime = Time.time;
		if(curTime > saveTime + intervalSecond){
			saveTime = curTime;
			return 1;
		}else{
			return 0;
		}
	}
	
	void SendData(byte[] data, ushort cmd){
		if(client.Connected){
			ushort len = (ushort)(data.Length + 5);
			byte[] sendData = new byte[len];
			sendData[0] = (byte)(len >> 8);
			sendData[1] = (byte)len;
			sendData[2] = 0;
			sendData[3] = (byte)(cmd >> 8);
			sendData[4] = (byte)cmd;
			Array.Copy(data, 0, sendData, 5, len - 5);
			client.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, new AsyncCallback(SendDataCallback), client);
		}
	}
	
	void ConnectCallback(IAsyncResult iar){
		try{
			client = (Socket)iar.AsyncState;
			client.EndConnect(iar);
			print ("connecting ok");
		}catch(SocketException){
			print ("connecting fail");
		}
	}
	
	void SendDataCallback(IAsyncResult iar){
		try{
			client = (Socket)iar.AsyncState;
			client.EndSend(iar);
			print ("send ok");
			client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), client);
		}catch(SocketException){
			print ("send fail");
		}
	}
	
	void ReceiveCallback(IAsyncResult iar){
		client = (Socket)iar.AsyncState;
		int recv = client.EndReceive(iar);
//		for(int i = 0; i < recv + 1;i++){
//			print (buffer[i]);
//		}
		string str = Encoding.UTF8.GetString(buffer, 0, recv);
		print ("receive msg : " + str);
	}
	
}
